package com.cqu.lpss.controller;

import com.aliyuncs.utils.StringUtils;
import com.cqu.lpss.pojo.*;
import com.cqu.lpss.service.impl.AdministorsImpl;
import com.cqu.lpss.service.impl.ContestantsImpl;
import com.cqu.lpss.service.impl.ProfessorsImpl;
import com.cqu.lpss.service.impl.ProjectImpl;
import com.cqu.lpss.utils.JwtUtils;
import com.cqu.lpss.utils.SMSUtils;
import com.cqu.lpss.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
//@CrossOrigin(origins = "*")
public class LoginController {
    @Autowired
    ContestantsImpl contestantsimpl;
    @Autowired
    AdministorsImpl administorsimpl;
    @Autowired
    ProfessorsImpl professorsimpl;
    @PostMapping("/login")
    public Result login(@RequestParam String id,@RequestParam String password,@RequestParam String picCode,@RequestParam String role){
        if(role.equals("administor")){
            Administors administors = new Administors();
            administors.setAdmId(id);
            administors.setAdmPassword(password);
            log.info("admin:{}",administors);
            Administors loginuser = administorsimpl.login(administors);
            if(loginuser!=null){
                HashMap<String, Object> claims = new HashMap<>();
                claims.put("userIndex",loginuser.getAdmIndex());
                claims.put("userId",loginuser.getAdmId());
                claims.put("userName",loginuser.getAdmName());
                claims.put("userClass",null);
                claims.put("roleName","admin");
                claims.put("roleId",'1');

                String jwt = JwtUtils.generateJwt(claims);
                return Result.success(jwt);
            }
            //登录失败，返回错误信息
            return Result.erro("用户名或密码错误");
        }
        if(role.equals("contestant")){
            Contestants contestants = new Contestants();
            contestants.setConId(id);
            contestants.setConPassword(password);
            Contestants loginuser = contestantsimpl.login(contestants);
            if(loginuser!=null){
                HashMap<String, Object> claims = new HashMap<>();
                claims.put("userIndex",loginuser.getConIndex());
                claims.put("userId",loginuser.getConId());
                claims.put("userName",loginuser.getConName());
                claims.put("userClass",loginuser.getConClass());
                claims.put("roleName","contestant");
                claims.put("roleId",'5');

                String jwt = JwtUtils.generateJwt(claims);
                return Result.success(jwt);
            }
            //登录失败，返回错误信息
            return Result.erro("用户名或密码错误");

        }

        if(role.equals("professor")){
            Professors professors = new Professors();
            professors.setProId(id);
            professors.setProPassword(password);
            Professors loginprof = professorsimpl.login(professors);
            //登录成功生成jwt令牌
            if(loginprof!=null){
                HashMap<String, Object> claims = new HashMap<>();
                claims.put("userIndex",loginprof.getProIndex());
                claims.put("userId"   ,loginprof.getProId());
                claims.put("userName",loginprof.getProName());
                claims.put("userClass",loginprof.getProClass());
                claims.put("roleName","professor");
                claims.put("roleId",loginprof.getProAuth().toString());
                String jwt = JwtUtils.generateJwt(claims);
                return Result.success(jwt);
            }
            //登录失败，返回错误信息
            return Result.erro("身份证或密码错误");

        }
        //登录失败，返回错误信息
        return Result.erro("用户名或密码错误");
    }
    @PostMapping("/register")
    public Result register(@RequestBody ConRegister data, HttpSession session){
        log.info("ConRegister:{}",data);
        Contestants postData = data.getPostData();
        String verificationCode = data.getVerificationCode();
        log.info("contestant:{}",postData);
        log.info("verificationCode:{}",verificationCode);

        Contestants con_sameId = contestantsimpl.findById(postData.getConId());
        String phone = postData.getConPhone();
        log.info("phone:{}",phone);
        if(con_sameId!=null){
            return Result.erro("SAME_CONID");
        }else{
            Object codeInSession = session.getAttribute(phone);
            log.info("sessionId：{}",session.getAttribute(phone.toString()).toString());
            if (codeInSession != null && codeInSession.equals(verificationCode)){
                postData.setConCreatetime(new Timestamp(System.currentTimeMillis()));
                postData.setConUpdatetime(new Timestamp(System.currentTimeMillis()));
                int ans = contestantsimpl.insert(postData);
                if(ans==1){
                    log.info("contestant_register:{}",postData);
                    return  Result.success();
                }else {
                    return Result.erro("注册错误，请联系管理员");
                }

            }else {
                return Result.erro("验证码错误");
            }
        }
    }

    @PostMapping("/RegistersendMsg")
    public Result RegistersendMsg(@RequestParam String phone, HttpSession session){
        if(StringUtils.isEmpty(phone)){
            return Result.erro("短信发送失败");
        }

//            2.随机生成四位验证
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码：{}",code);
//      4.需要将生成的验证码保存到session中
            session.setAttribute(phone,code);
            log.info("phone:{}",phone);
            log.info(session.getId());
//      3.调用阿里云提供的短信服务
            SMSUtils.sendMessage("CQU文学评奖大赛","SMS_465701354",phone,code);
            return Result.success("验证码短信发送成功");





    }
    @PostMapping("/sendMsg")
    public Result sendMsg(@RequestParam String phone, HttpSession session){
        if(StringUtils.isEmpty(phone)){
            return Result.erro("短信发送失败");
        }
        Contestants contestants = contestantsimpl.findByPhone(phone);
        Professors professors = professorsimpl.findByPhone(phone);
        Administors administors = administorsimpl.findByPhone(phone);
        if(contestants!=null||professors!=null||administors!= null){
//            2.随机生成四位验证
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码：{}",code);
//      4.需要将生成的验证码保存到session中
            session.setAttribute(phone,code);
            log.info("phone:{}",phone);
            log.info(session.getId());
//      3.调用阿里云提供的短信服务
            SMSUtils.sendMessage("CQU文学评奖大赛","SMS_465701354",phone,code);
            return Result.success("验证码短信发送成功");
        }else {
            return  Result.erro("号码未注册");
        }




    }
    @PostMapping("loginbyphone")
    public Result loginbyPhone(@RequestParam String phone,@RequestParam String verificationCode,
                               @RequestParam String role, HttpSession session){
        log.info("params:{}",phone);
        log.info("params:{}",verificationCode);
//      3. 从Session中获取保存的验证码
        Object codeInSession = session.getAttribute(phone);
        log.info("sessionId：{}",session.getAttribute(phone).toString());
//      4.验证该手机号是否注册
        if(role.equals("administor")){
            Administors loginuser = administorsimpl.findByPhone(phone);
            if(loginuser!=null){
    //          4. 进行验证码比对(页面提交的验证码和Session中保存的验证码比对)
                if (codeInSession != null && codeInSession.equals(verificationCode)) {
    //          5.对比成功，说明登录成功
                    HashMap<String, Object> claims = new HashMap<>();
                    claims.put("userIndex",loginuser.getAdmIndex());
                    claims.put("userId",loginuser.getAdmId());
                    claims.put("userName",loginuser.getAdmName());
                    claims.put("userClass",null);
                    claims.put("roleName","admin");
                    claims.put("roleId",'1');
                    String jwt = JwtUtils.generateJwt(claims);
                    return Result.success(jwt);

                }
            }
            return Result.erro("验证码错误");
        }
        if(role.equals("contestant")){
            Contestants loginuser = contestantsimpl.findByPhone(phone);
            if(loginuser!=null){
                //          4. 进行验证码比对(页面提交的验证码和Session中保存的验证码比对)
                if (codeInSession != null && codeInSession.equals(verificationCode)) {
                    //          5.对比成功，说明登录成功
                    HashMap<String, Object> claims = new HashMap<>();
                    claims.put("userIndex",loginuser.getConIndex());
                    claims.put("userId",loginuser.getConId());
                    claims.put("userName",loginuser.getConName());
                    claims.put("userClass",loginuser.getConClass());
                    claims.put("roleName","contestant");
                    claims.put("roleId",'5');

                    String jwt = JwtUtils.generateJwt(claims);
                    return Result.success(jwt);

                }
            }
            return Result.erro("验证码错误");
        }
        if(role.equals("professor")){
            Professors loginuser = professorsimpl.findByPhone(phone);
            if(loginuser!=null){
                //          4. 进行验证码比对(页面提交的验证码和Session中保存的验证码比对)
                if (codeInSession != null && codeInSession.equals(verificationCode)) {
                    //          5.对比成功，说明登录成功
                    HashMap<String, Object> claims = new HashMap<>();
                    claims.put("userIndex",loginuser.getProIndex());
                    claims.put("userId",loginuser.getProId());
                    claims.put("userName",loginuser.getProName());
                    claims.put("userClass",loginuser.getProClass());
                    claims.put("roleName","professor");
                    claims.put("roleId",loginuser.getProAuth().toString());

                    String jwt = JwtUtils.generateJwt(claims);
                    return Result.success(jwt);

                }

            }
            return Result.erro("验证码错误");
        }
        return Result.erro("该电话未注册");


    }
    @PostMapping("verification")
    public Result verification(@RequestParam String phone,@RequestParam String verificationCode,
                               @RequestParam String role, HttpSession session){
        log.info("params:{}",phone);
        log.info("params:{}",verificationCode);
//      3. 从Session中获取保存的验证码
        Object codeInSession = session.getAttribute(phone);
        log.info("sessionId：{}",session.getAttribute(phone).toString());
//      4.验证该手机号是否注册
        if(role.equals("administor")){
            Administors loginuser = administorsimpl.findByPhone(phone);
            if(loginuser!=null){
                //          4. 进行验证码比对(页面提交的验证码和Session中保存的验证码比对)
                if (codeInSession != null && codeInSession.equals(verificationCode)) {
                    //          5.对比成功，说明登录成功

                    return Result.success("验证成功");

                }
            }
            return Result.erro("验证码错误");
        }
        if(role.equals("contestant")){
            Contestants loginuser = contestantsimpl.findByPhone(phone);
            if(loginuser!=null){
                //          4. 进行验证码比对(页面提交的验证码和Session中保存的验证码比对)
                if (codeInSession != null && codeInSession.equals(verificationCode)) {
                    //          5.对比成功，说明登录成功
                    return Result.success("验证成功");

                }
            }
            return Result.erro("验证码错误");
        }
        if(role.equals("professor")){
            Professors loginuser = professorsimpl.findByPhone(phone);
            if(loginuser!=null){
                //          4. 进行验证码比对(页面提交的验证码和Session中保存的验证码比对)
                if (codeInSession != null && codeInSession.equals(verificationCode)) {
                    //          5.对比成功，说明登录成功
                    return Result.success("验证成功");

                }

            }
            return Result.erro("验证码错误");
        }
        return Result.erro("该电话未注册");


    }
}
